import React, {useEffect} from 'react'
import {Badge, Button, Card, Col, Empty, Input, List, message, Modal, Row, Space, Switch, Tag, Typography} from 'antd'
import {CheckCircle, Code, Database, FileText, Settings, Table, Target} from 'lucide-react'
import type {DataSourceTreeNode} from '@/components/business/DataSourceTree/types'
import {useDataSourceStore} from '@/stores/dataSourceStore'

const { Title, Text } = Typography

const TablePanel: React.FC<{ node: DataSourceTreeNode }> = ({ node }) => {
  const tableName = node.title as string
  const databaseName = node.parentId || ''
  const catalogName = (node as any).catalogName || ''
  // 兼容：若树没有 catalogName，可通过两级 parentId 获取，这里简化假设 parentId 为数据库标识
  const { setEnabled, updateSystemCode, generateDorisScript, loadColumns, loadDimensions, columns, dimensions } = useDataSourceStore()
  const [msgApi, contextHolder] = message.useMessage()
  const [enabled, setEnabledLocal] = React.useState<boolean>(!!node.enabled)
  const [systemCode, setSystemCodeLocal] = React.useState<string>('')
  const [script, setScript] = React.useState<string>('')
  const [scriptVisible, setScriptVisible] = React.useState<boolean>(false)

  useEffect(() => {
    if (catalogName && databaseName && tableName) {
      loadColumns(catalogName, databaseName, tableName)
      loadDimensions(catalogName, databaseName, tableName)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [catalogName, databaseName, tableName])

  const notify = (content: string, type: 'success' | 'error' = 'success') => msgApi.open({ type, content })

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {contextHolder}

      {/* 标题卡片 */}
      <Card style={{ border: 'none', background: 'linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Table size={28} style={{ color: '#ffffff', marginRight: 12 }} />
            <div>
              <Title level={3} style={{ color: '#ffffff', margin: 0, textShadow: '0 2px 4px rgba(0,0,0,0.3)' }}>
                {tableName}
              </Title>
              <Text style={{ color: 'rgba(255, 255, 255, 0.85)', fontSize: 14 }}>
                表结构管理
              </Text>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <Badge
              status={enabled ? 'success' : 'error'}
              text={
                <span style={{ color: '#ffffff', fontSize: 12 }}>
                  {enabled ? '已启用' : '已禁用'}
                </span>
              }
            />
            <Tag style={{ background: 'rgba(255, 255, 255, 0.2)', border: 'none', color: '#ffffff' }}>
              数据表
            </Tag>
          </div>
        </div>
      </Card>

      {/* 操作区域 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={16}>
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <FileText size={16} style={{ marginRight: 8, color: '#1890ff' }} />
                脚本生成
              </div>
            }
            style={{ height: '100%' }}
          >
            <Space direction="vertical" style={{ width: '100%' }} size="middle">
              <div>
                <Text type="secondary" style={{ marginBottom: 12, display: 'block' }}>
                  生成 Doris 数据仓库建表脚本
                </Text>
                <Button
                  type="primary"
                  icon={<Database size={14} />}
                  onClick={async () => {
                    if (!catalogName || !databaseName) return notify('缺少目录或数据库名', 'error')
                    const s = await generateDorisScript(catalogName, databaseName, tableName)
                    setScript(s)
                    setScriptVisible(true)
                  }}
                  block
                  size="large"
                >
                  生成 Doris 建表脚本
                </Button>
              </div>
            </Space>
          </Card>
        </Col>

        <Col xs={24} lg={8}>
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Settings size={16} style={{ marginRight: 8, color: '#1890ff' }} />
                配置管理
              </div>
            }
            style={{ height: '100%' }}
          >
            <Space direction="vertical" style={{ width: '100%' }} size="middle">
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <CheckCircle size={14} style={{ marginRight: 6, color: enabled ? '#52c41a' : '#c9cdd4' }} />
                  <Text>启用状态</Text>
                </div>
                <Switch
                  checked={enabled}
                  onChange={async (v) => {
                    setEnabledLocal(v)
                    if (!catalogName || !databaseName) return notify('缺少目录或数据库名', 'error')
                    await setEnabled({ level: 'table', catalogName, databaseName, tableName, enabled: v })
                  }}
                />
              </div>

              <div>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                  <Code size={14} style={{ marginRight: 6, color: '#86909c' }} />
                  <Text>系统编码</Text>
                </div>
                <Input.Group compact>
                  <Input
                    style={{ width: 'calc(100% - 60px)' }}
                    value={systemCode}
                    onChange={(e) => setSystemCodeLocal(e.target.value)}
                    placeholder="输入系统编码"
                    size="small"
                  />
                  <Button
                    size="small"
                    type="primary"
                    onClick={async () => {
                      if (!systemCode) return notify('请先输入系统编码', 'error')
                      if (!catalogName || !databaseName) return notify('缺少目录或数据库名', 'error')
                      await updateSystemCode({ level: 'table', catalogName, databaseName, tableName, systemCode })
                      notify('系统编码已更新')
                    }}
                  >
                    保存
                  </Button>
                </Input.Group>
              </div>
            </Space>
          </Card>
        </Col>
      </Row>

      {/* 表结构信息 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Database size={16} style={{ marginRight: 8, color: '#1890ff' }} />
                  列字段
                </div>
                <Badge count={columns?.length || 0} style={{ backgroundColor: '#1890ff' }} />
              </div>
            }
            style={{ height: '400px' }}
            styles={{ body: { height: 'calc(100% - 57px)', overflow: 'auto' } }}
          >
            {columns && columns.length > 0 ? (
              <List
                size="small"
                dataSource={columns}
                renderItem={(c, index) => (
                  <List.Item
                    style={{
                      padding: '8px 12px',
                      borderRadius: 6,
                      marginBottom: 4,
                      background: index % 2 === 0 ? '#fafbfc' : '#ffffff',
                      border: '1px solid #f0f2f5'
                    }}
                  >
                    <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
                      <Database size={12} style={{ marginRight: 8, color: '#86909c' }} />
                      <Text strong style={{ marginRight: 8 }}>{c?.name}</Text>
                      <Tag size="small" style={{ fontSize: 11 }}>{c?.type}</Tag>
                    </div>
                  </List.Item>
                )}
              />
            ) : (
              <Empty
                image={<Database size={32} style={{ color: '#c9cdd4' }} />}
                description="暂无列字段数据"
                style={{ padding: '40px 0' }}
              />
            )}
          </Card>
        </Col>

        <Col xs={24} lg={12}>
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <Target size={16} style={{ marginRight: 8, color: '#1890ff' }} />
                  维度定义
                </div>
                <Badge count={dimensions?.length || 0} style={{ backgroundColor: '#52c41a' }} />
              </div>
            }
            style={{ height: '400px' }}
            styles={{ body: { height: 'calc(100% - 57px)', overflow: 'auto' } }}
          >
            {dimensions && dimensions.length > 0 ? (
              <List
                size="small"
                dataSource={dimensions}
                renderItem={(d, index) => (
                  <List.Item
                    style={{
                      padding: '12px',
                      borderRadius: 6,
                      marginBottom: 8,
                      background: index % 2 === 0 ? '#fafbfc' : '#ffffff',
                      border: '1px solid #f0f2f5'
                    }}
                  >
                    <div style={{ display: 'flex', flexDirection: 'column', width: '100%' }}>
                      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 4 }}>
                        <Target size={12} style={{ marginRight: 6, color: '#52c41a' }} />
                        <Text strong>{d?.name}</Text>
                      </div>
                      <Text type="secondary" style={{ fontSize: 12, lineHeight: 1.4 }}>
                        {d?.description}
                      </Text>
                    </div>
                  </List.Item>
                )}
              />
            ) : (
              <Empty
                image={<Target size={32} style={{ color: '#c9cdd4' }} />}
                description="暂无维度定义数据"
                style={{ padding: '40px 0' }}
              />
            )}
          </Card>
        </Col>
      </Row>

      {/* 脚本预览模态框 */}
      <Modal
        open={scriptVisible}
        title={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <FileText size={20} style={{ marginRight: 8, color: '#1890ff' }} />
            Doris 建表脚本 - {tableName}
          </div>
        }
        onCancel={() => setScriptVisible(false)}
        footer={
          <Button
            type="primary"
            onClick={() => setScriptVisible(false)}
            icon={<CheckCircle size={14} />}
          >
            关闭
          </Button>
        }
        width={900}
        style={{ top: 20 }}
      >
        <Card
          size="small"
          style={{
            background: '#1f2937',
            border: 'none',
            maxHeight: '60vh',
            overflow: 'auto'
          }}
        >
          <pre style={{
            whiteSpace: 'pre-wrap',
            color: '#e5e7eb',
            fontFamily: 'Monaco, Consolas, "Courier New", monospace',
            fontSize: 13,
            lineHeight: 1.5,
            margin: 0
          }}>
            {script}
          </pre>
        </Card>
      </Modal>
    </div>
  )
}

export default TablePanel